package com.jwm.power.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.jwm.power.mapper.OperateMapper;
import com.jwm.power.mapper.QueryMapper;
import com.jwm.power.model.common.EnumOperate;
import com.jwm.power.model.common.EnumResult;
import com.jwm.power.model.entity.Formcustoms;
import com.jwm.power.model.entity.Logs;
import com.jwm.power.model.entity.Menus;
import com.jwm.power.model.entity.Users;
import com.jwm.power.model.reponse.ResponseData;
import com.jwm.power.repository.FormcustomsRepository;
import com.jwm.power.repository.LogsRepository;
import com.jwm.power.repository.MenusRepository;
import com.jwm.power.service.OperateService;
import com.jwm.power.util.Ut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.ServletRequestDataBinder;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class OperateServiceImpl implements OperateService {

    @Autowired
    private LogsRepository logsRepository;
    @Autowired
    private OperateMapper operateMapper;
    @Autowired
    private QueryMapper queryMapper;
    @Autowired
    private MenusRepository menusRepository;

    //  删除数据
    @Override
    public ResponseData DeleteDatas(HttpServletRequest request) {
        try {
            String dataId = request.getParameter("dataId");
            String dataType = request.getParameter("dataType");
            Users users = (Users) StpUtil.getSession().get("users");
            //  检查部门是否存在人员数据
            if (dataType.equals("depts")) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("tName", "Users");
                map.put("strCell", "userid");
                map.put("strWhere", " where deptcode  like '" + dataId + "%'");
                List<Map<String, Object>> mapList = queryMapper.queryDefinedDatas(map);
                if (mapList.size() > 0) {
                    return new ResponseData(EnumResult.USER_FAIL_DEPT, null);
                }
            }
            HashMap<String, Object> map = getDelMap(dataType, dataId);
            // operateMapper.deleteDefined(map);
            switch (dataType) {
                case "jobs":
                    //  删除职务权限数据
                    map = new HashMap<>();
                    map.put("tName", "JobMenus");
                    map.put("strWhere", "jobcode ='" + dataId + "'");
                    operateMapper.deleteDefined(map);
                    break;
                case "tasklst":
                    map = new HashMap<>();
                    map.put("tName", "TaskLst");
                    map.put("strWhere", "id ='" + dataId + "'");
                    operateMapper.deleteDefined(map);
                    break;
                case "inquiry":
                    map = new HashMap<>();
                    map.put("tName", "inquirydata");
                    map.put("strWhere", "id = " + dataId);
                    operateMapper.deleteDefined(map);
            }
            //  添加日志
            Logs log = Ut.SaveLog(dataType, dataId, EnumOperate.DELETE, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    //  批量删除
    @Override
    public ResponseData DeleteAllDatas(HttpServletRequest request) {
        try {
            String dataIds = request.getParameter("dataIds");
            String dataType = request.getParameter("dataType");
            Users users = (Users) StpUtil.getSession().get("users");
            //  检查部门是否存在人员数据
            if (dataType.equals("depts")) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("tName", "Users");
                map.put("strCell", "userid");
                map.put("strWhere", " where charindex( ','+deptcode+',','," + dataIds + "') > 0");
                List<Map<String, Object>> mapList = queryMapper.queryDefinedDatas(map);
                if (mapList.size() > 0) {
                    return new ResponseData(EnumResult.USER_FAIL_DEPT, null);
                }
            }
            for (String dataId : dataIds.split(",")) {
                HashMap<String, Object> map = getDelMap(dataType, dataId);
                map = new HashMap<>();
                switch (dataType) {
                    case "jobs":
                        //  删除职务权限数据
                        map.put("tName", "JobMenus");
                        map.put("strWhere", "jobcode ='" + dataId + "'");
                        operateMapper.deleteDefined(map);
                        break;
                }
                if(dataType.equals("tasklst")){
                    map.put("tName","TaskLst");
                    map.put("strWhere", "id ='" + dataId + "'");
                    operateMapper.deleteDefined(map);
                }
            }
            //  添加日志
            Logs log = Ut.SaveLog(dataType, dataIds, EnumOperate.DELETE, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    public HashMap<String, Object> getDelMap(String dataType, String dataId) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        switch (dataType) {
            case "menus":
                map.put("tName", "menus");
                map.put("strWhere", "menucode like '" + dataId + "%'");
                break;
            case "depts":
                map.put("tName", "depts");
                map.put("strWhere", "deptcode like '" + dataId + "%'");
                break;
            case "dics":
                map.put("tName", "Sys_Dics");
                map.put("strWhere", "diccode like '" + dataId + "%'");
                break;
            case "notices":
                map.put("tName", "Sys_Notices");
                map.put("strWhere", "ID ='" + dataId + "'");
                break;
            case "jobs":
                map.put("tName", "deptjob");
                map.put("strWhere", "jobcode like '" + dataId + "%'");
                break;
            case "msgs":
                map.put("tName", "Users_Messages");
                map.put("strWhere", "ID ='" + dataId + "'");
                break;
            case "users":
                map.put("tName", "users");
                map.put("strWhere", "userid ='" + dataId + "'");
                break;
            case "formCustoms":
                map.put("tName", "formcustoms");
                map.put("strWhere", "fid ='" + dataId + "'");
                break;
            case "cus":
                map.put("tName", "Xsfw_CusArchive");
                map.put("strWhere", "id ='" + dataId + "'");
                break;
            case "sources":
                map.put("tName", "Xsfw_CusSource");
                map.put("strWhere", "code like '" + dataId + "%'");
                break;
            case "orderType":
                map.put("tName", "WorkOrderTypes");
                map.put("strWhere", "TId ='" + dataId + "'");
                break;
            case "inquiry":
                map.put("tName","inquiryData");
                map.put("strWhere", "id='" + dataId +"'");
                break;
        }
        return map;
    }

    //  设置数据排序
    @Override
    public ResponseData SetDataSn(HttpServletRequest request) {
        try {
            String dataId = request.getParameter("dataId");
            String dataType = request.getParameter("dataType");
            String snType = request.getParameter("snType");
            Users users = (Users) StpUtil.getSession().get("users");

            HashMap<String, Object> map = new HashMap<>();
            List<Map<String, Object>> mapList = new ArrayList<>();
            switch (dataType) {
                case "menus":
                    Menus menus = menusRepository.findByMenucode(dataId);
                    if (menus != null) {
                        //  获取相邻序号
                        map.put("tName", "menus");
                        map.put("strCell", " top 1 orderbyid,menucode ");
                        map.put("strWhere", " where parentcode='" + menus.getParentcode() + "' and orderbyid "
                                + (snType.equals("0") ? "<" : ">") + menus.getOrderbyid() + " order by orderbyid" +
                                (snType.equals("0") ? " desc " : ""));
                        mapList = queryMapper.queryDefinedDatas(map);
                        if (mapList.size() > 0) {
                            map = new HashMap<>();
                            map.put("tName", "menus");
                            map.put("values", " orderbyid='" + menus.getOrderbyid() + "'");
                            map.put("strWhere", " where menucode='" + mapList.get(0).get("menucode") + "'");
                            operateMapper.updateDefined(map);
                            menus.setOrderbyid(Integer.valueOf(mapList.get(0).get("orderbyid").toString()));
                            menusRepository.save(menus);
                        }
                    }
                    break;
            }
            //  添加日志
            Logs log = Ut.SaveLog(dataType, dataId, snType.equals("0") ? EnumOperate.ASC : EnumOperate.DESC, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    //  阅读公告
    @Override
    public ResponseData ReadNotices(HttpServletRequest request) {
        try {
            String dataId = request.getParameter("dataId");
            String dataType = request.getParameter("dataType");
            Users users = (Users) StpUtil.getSession().get("users");

            HashMap<String, Object> map = new HashMap<>();
            map.put("tName", "Sys_NoticesUser");
            String values = " Status=1" ;
            if(dataType.equals("1")){
                values +=",RStatus=1";
            }
            map.put("values",values);
            map.put("strWhere", " where nid ='" + dataId + "' and userid=" + users.getUserid());
            operateMapper.updateDefined(map);
            //  添加日志
            Logs log = Ut.SaveLog("readNotice", dataId, EnumOperate.EDIT, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    //  数据提交
    @Override
    public ResponseData SubmitDatas(HttpServletRequest request) {
        try {
            String dataId = request.getParameter("dataId");
            String dataType = request.getParameter("dataType");
            Users users = (Users) StpUtil.getSession().get("users");
            HashMap<String, Object> map = getSubmitMap(dataType, dataId);
            operateMapper.updateDefined(map);

            //  添加日志
            Logs log = Ut.SaveLog(dataType, dataId, EnumOperate.SUBMIT, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    // 撤回表单
    @Override
    public ResponseData TakebackDatas(HttpServletRequest request) {
        try {
            String dataId = request.getParameter("dataId");
            String dataType = request.getParameter("dataType");
            Users users = (Users) StpUtil.getSession().get("users");
            HashMap<String, Object> map = getTakebackMap(dataType, dataId);
            operateMapper.updateDefined(map);
            Logs log = Ut.SaveLog(dataType, dataId, EnumOperate.SUBMIT, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, null);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }
    // 完成表单
    @Override
    public ResponseData ComplateDatas(HttpServletRequest request) {
        try {
            String dataIds = request.getParameter("dataId");
            String dataType = request.getParameter("dataType");
            Users users = (Users) StpUtil.getSession().get("users");
            for (String dataId : dataIds.split(",")) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("tName", "inquiryData");
                String values = " formstatus=3";
                map.put("values", values);
                map.put("strWhere", " where id ='" + dataId + "'");
                operateMapper.updateDefined(map);
            }
            Logs log = Ut.SaveLog(dataType, dataIds, EnumOperate.SUBMIT, users);
            logsRepository.save(log);
            return new ResponseData(EnumResult.SUCCESS, null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseData(EnumResult.Exception.getCode(), e.getMessage(), null);
        }
    }

    // 调用的getsubmitmap 方法，通过dataType获取对应的更新值并做响应。
    public HashMap<String, Object> getSubmitMap(String dataType, String dataId) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        switch (dataType) {
            case "cus":
                map.put("tName", "Xsfw_CusArchive");
                map.put("values", "status=1");
                map.put("strWhere", " where id = '" + dataId + "'");
                break;
            case "tasklst":
                map.put("tName", "TaskLst");
                map.put("values", "taskstatus=-1");
                map.put("strWhere", " where id = '" + dataId + "'");
                break;
            case "inquiry":
                map.put("tName", "inquirydata");
                map.put("values", "formstatus=0");
                map.put("strWhere", " where id =" + dataId );
        }
        return map;
    }
    public HashMap<String, Object> getTakebackMap(String dataType, String dataId) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        switch (dataType) {
            case "tasklst":
                map.put("tName", "TaskLst");
                map.put("values","taskstatus=2");
                map.put("strWhere", " where id ='" + dataId + "'");
            case "inquiry":
                map.put("tName", "inquirydata");
                map.put("values", "formstatus=-1");
                map.put("strWhere", " where id=" + dataId );
        }
        return map;
    }
}
